const { verify } = require("jsonwebtoken")
/**
 * 
 * @param {token} token 
 * @param {secret} secret 
 * 注释：这是用来处理API接口权限验证的中间件
 */
function verifyToken(token, secret) {
  return new Promise(function (resolve, reject) {
    verify(token, secret, (err, user) => {
      if (err) {
        reject(err)
      } else {
        resolve(user)
      }
    })
  })
}
module.exports = function (options, app) {
  let jwtSecret = app.config.jwtSecret
  return async (ctx, next) => {
    let token = ctx.get("X-Token")
    if (token) {
      try {
        let user = await verifyToken(token, jwtSecret)
        ctx.session.user = user
        await next()
      } catch (error) {
        ctx.status = 403
        ctx.body = { code: 1, error: "token不合法" }
      }
    } else {
      ctx.status = 403
      ctx.body = { code: 1, error: "token不存在" }
    }
  }
}
